﻿using Senparc.Weixin.MP.AdvancedAPIs;
using Senparc.Weixin.MP.CommonAPIs;
using Senparc.Weixin.MP.Entities;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using System.Timers;

namespace WeixinImageDownLoadServer
{
    public partial class WeixinImageDownLoad : ServiceBase
    {
        Timer timer1;
        public WeixinImageDownLoad()
        {

            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            timer1 = new Timer();
            timer1.Interval = Convert.ToInt32(ConfigurationSettings.AppSettings["Interval"] ?? "10") * 60 * 1000;//10分钟处理一次
            timer1.Elapsed += new System.Timers.ElapsedEventHandler(timer1_Elapsed);
            timer1.Enabled = true;
        }

        protected override void OnStop()
        {
        }

        private void timer1_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            using (UnitOfWork unitOfWork = new UnitOfWork())
            {
                var orderImageList = unitOfWork.Context.Sql(@"select a.* from orderimage a 
                                        left JOIN orders b on a.oid=b.oid
                                        where b.source=1 and a.serverid is not null").QueryMany<OrderImage>();
                var accessToken = GetToken(ConfigurationSettings.AppSettings["WeixinAppId"], ConfigurationSettings.AppSettings["WeixinAppSecret"]);
                if (orderImageList != null)
                {
                    //先移除事件
                    AppReportManager.Instance.RemoveListener<QiniuUploadResult>(doResult);
                    AppReportManager.Instance.AddListener<QiniuUploadResult>(doResult);
                    foreach (OrderImage orderImage in orderImageList)
                    {
                        MemoryStream stream = new MemoryStream();
                        MediaApi.Get(accessToken.access_token, orderImage.serverid, stream);
                        stream.Position = 0;
                        LogUtil.Info("pid:" + orderImage.pid + "|微信ID:" + orderImage.serverid + "|文件大小:" + stream.Length);
                        string filename = Guid.NewGuid().ToString().Replace("-", "") + ".jpg";
                        QiniuUploadResult uploadResult = new QiniuUploadTask(filename, stream, orderImage, orderImage.pid).Run(null);
                    }
                }
            }
        }

        public void doResult(QiniuUploadResult qnresult)
        {
            //bool result = false;
            if (qnresult.success)
            {
                using (UnitOfWork unitOfWork = new UnitOfWork())
                {
                    unitOfWork.Context.Update("orderimage")
                                     .Column("url", qnresult.url)
                                     .Where("pid", qnresult.pid)
                                     .Execute();
                }
                //return result;
            }
            else
            {
                //result = false;
                LogUtil.Info("pid:" + qnresult.pid + "|message:" + qnresult.msg);
                //return result;
            }
        }

        private AccessTokenResult GetToken(string appId, string appSecret)
        {
            AccessTokenResult result = new AccessTokenResult();
            if (!AccessTokenContainer.CheckRegistered(appId))//检查是否已经注册
            {
                AccessTokenContainer.Register(appId, appSecret);//如果没有注册则进行注册
            }
            result = AccessTokenContainer.GetAccessTokenResult(appId); //获取AccessToken结果
            return result;
        }
    }
}
